package usbcali.edu.presentation.backEndBeans;

import com.icesoft.faces.async.render.RenderManager;
import com.icesoft.faces.async.render.Renderable;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.selectinputdate.SelectInputDate;
import com.icesoft.faces.context.DisposableBean;
import com.icesoft.faces.webapp.xmlhttp.FatalRenderingException;
import com.icesoft.faces.webapp.xmlhttp.PersistentFacesState;
import com.icesoft.faces.webapp.xmlhttp.RenderingException;
import com.icesoft.faces.webapp.xmlhttp.TransientRenderingException;




import usbcali.edu.exceptions.*;

import usbcali.edu.persistencia.*;
import usbcali.edu.persistencia.control.UsuariosLogic;
import usbcali.edu.persistencia.dto.ReservasDTO;

import usbcali.edu.presentation.businessDelegate.BusinessDelegatorView;

import usbcali.edu.utilities.*;

import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.Vector;

import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;


/**
*
*
* @author Zathura Code Generator http://code.google.com/p/zathura
*
*/
public class ReservasView extends DataSource implements Renderable,
    DisposableBean {
    private HtmlInputText txtCodSala_Salaxtforma;
    private HtmlInputText txtCodTforma_Salaxtforma;
    private HtmlInputText txtCodSolicitude_SolEventos;
    private HtmlInputText txtLoggin_Usuarios;
    private HtmlInputText txtCodReservas;
    private SelectInputDate txtFechaEvento;
    private SelectInputDate txtFechaReserva;
    private HtmlCommandButton btnSave;
    private HtmlCommandButton btnModify;
    private HtmlCommandButton btnDelete;
    private HtmlCommandButton btnClear;
    private boolean renderDataTable;
    private boolean flag = true;
    private RenderManager renderManager;
    private PersistentFacesState state = PersistentFacesState.getInstance();
    private List<Reservas> reservas;
    private List<ReservasDTO> reservasDTO;

    
    
    private HtmlInputText txtTema;
    private HtmlInputText txtNumeroParticipan;
    private HtmlInputText txtDescripcion;
    private List<SelectItem>valoresComboTFormaxSala;
    private BigDecimal valoresItemSalaxForma;
    private BigDecimal valoresItemTformaxSala;
    private List<SelectItem>valoresComboSala;
    private List<SolEventos>listSolEventos;
    private List<SelectItem>valoresComboNSolici;
    private BigDecimal valoresItemNSolicitud;
    private List<RHorariosReserva> listaHorarioxSala;
    private List<SelectItem>valoresCombohora;
    private List<String>valoresLeyendCombohora;
    private String valoresItemHora;
    Vector<String> almacenarHoras = new Vector();
    
    
    public ReservasView() {
        super("");
    }

    public String action_clear() {
        txtCodSala_Salaxtforma.setValue(null);
        txtCodSala_Salaxtforma.setDisabled(true);
        txtCodTforma_Salaxtforma.setValue(null);
        txtCodTforma_Salaxtforma.setDisabled(true);
        txtCodSolicitude_SolEventos.setValue(null);
        txtCodSolicitude_SolEventos.setDisabled(true);
        txtLoggin_Usuarios.setValue(null);
        txtLoggin_Usuarios.setDisabled(true);
        txtFechaEvento.setValue(null);
        txtFechaEvento.setDisabled(true);
        txtFechaReserva.setValue(null);
        txtFechaReserva.setDisabled(true);
        txtCodReservas.setValue(null);
        txtCodReservas.setDisabled(false);
        btnSave.setDisabled(true);
        btnDelete.setDisabled(true);
        btnModify.setDisabled(true);
        btnClear.setDisabled(false);

        return "";
    }

    public void listener_txtId(ValueChangeEvent event) {
        if ((event.getNewValue() != null) && !event.getNewValue().equals("")) {
            Reservas entity = null;

            try {
                String codReservas = new String(txtCodReservas.getValue()
                                                              .toString());
                entity = BusinessDelegatorView.getReservas(codReservas);
            } catch (Exception e) {
                // TODO: handle exception
            }

            if (entity == null) {
                txtCodSala_Salaxtforma.setDisabled(false);
                txtCodTforma_Salaxtforma.setDisabled(false);
                txtCodSolicitude_SolEventos.setDisabled(false);
                txtLoggin_Usuarios.setDisabled(false);
                txtFechaEvento.setDisabled(false);
                txtFechaReserva.setDisabled(false);
                txtCodReservas.setDisabled(false);
                btnSave.setDisabled(false);
                btnDelete.setDisabled(true);
                btnModify.setDisabled(true);
                btnClear.setDisabled(false);
            } else {
                txtFechaEvento.setValue(entity.getFechaEvento());
                txtFechaEvento.setDisabled(false);
                txtFechaReserva.setValue(entity.getFechaReserva());
                txtFechaReserva.setDisabled(false);
                txtCodSala_Salaxtforma.setValue(entity.getSalaxtforma().getId()
                                                      .getCodSala());
                txtCodSala_Salaxtforma.setDisabled(false);
                txtCodTforma_Salaxtforma.setValue(entity.getSalaxtforma().getId()
                                                        .getCodTforma());
                txtCodTforma_Salaxtforma.setDisabled(false);
                txtCodSolicitude_SolEventos.setValue(entity.getSolEventos()
                                                           .getCodSolicitude());
                txtCodSolicitude_SolEventos.setDisabled(false);
                txtLoggin_Usuarios.setValue(entity.getUsuarios().getLoggin());
                txtLoggin_Usuarios.setDisabled(false);
                txtCodReservas.setValue(entity.getCodReservas());
                txtCodReservas.setDisabled(true);
                btnSave.setDisabled(true);
                btnDelete.setDisabled(false);
                btnModify.setDisabled(false);
                btnClear.setDisabled(false);
            }
        }
    }

    public String action_save() {
        try {
          /*  BusinessDelegatorView.saveReservas(FacesUtils.checkString(
                    txtCodReservas), FacesUtils.checkDate(txtFechaEvento),
                FacesUtils.checkDate(txtFechaReserva),
                FacesUtils.checkString(txtCodSala_Salaxtforma),
                FacesUtils.checkString(txtCodTforma_Salaxtforma),
                FacesUtils.checkString(txtCodSolicitude_SolEventos),
                FacesUtils.checkString(txtLoggin_Usuarios));*/
        	
UsuariosLogic logicaUsuario=new UsuariosLogic();
     		
     		List<Usuarios>	 consFun=logicaUsuario.consultarFuncionariPorUsuari(txtLoggin_Usuarios.getValue().toString());
     		
     		String cuenta=null;
     		if(consFun  != null){
				
				for(Usuarios objEn : consFun){
					objEn.getFuncionarios().getCedula();
					cuenta=objEn.getFuncionarios().getFNombre().toString();
					}
			}
        	
        	 BusinessDelegatorView.saveReservas(FacesUtils.checkString(
                     txtCodReservas), FacesUtils.checkDate(txtFechaEvento),
                 FacesUtils.checkDate(txtFechaReserva),
                 valoresItemSalaxForma,
                 valoresItemTformaxSala,
                 FacesUtils.checkString(txtLoggin_Usuarios),
                 valoresItemNSolicitud.toString(),                
                 FacesUtils.checkLong(txtNumeroParticipan),cuenta );
           // FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYSAVED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_delete() {
        try {
            BusinessDelegatorView.deleteReservas(FacesUtils.checkString(
                    txtCodReservas));
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYDELETED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modify() {
        try {
        	String cuenta="";
            BusinessDelegatorView.updateReservas(FacesUtils.checkString(
                    txtCodReservas), FacesUtils.checkDate(txtFechaEvento),
                FacesUtils.checkDate(txtFechaReserva),
                FacesUtils.checkBigDecimal(txtCodSala_Salaxtforma),
                FacesUtils.checkBigDecimal(txtCodTforma_Salaxtforma),
                FacesUtils.checkString(txtCodSolicitude_SolEventos),
                FacesUtils.checkString(txtLoggin_Usuarios),FacesUtils.checkLong(txtNumeroParticipan),cuenta);
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
            action_clear();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        return "";
    }

    public String action_modifyWitDTO(String codReservas, Date fechaEvento,
            Date fechaReserva, BigDecimal sfCodSala_Salaxtforma,
            BigDecimal sfCodTforma_Salaxtforma,
            String loggin_Usuarios,String numeroSolic,Long numeParti,String cuenta) throws Exception {
        try {
            BusinessDelegatorView.updateReservas(codReservas, fechaEvento,
                fechaReserva, sfCodSala_Salaxtforma,sfCodTforma_Salaxtforma,loggin_Usuarios,
                numeroSolic,numeParti, cuenta);
            renderManager.getOnDemandRenderer("ReservasView").requestRender();
            FacesUtils.addInfoMessage(ZMessManager.ENTITY_SUCCESFULLYMODIFIED);
        } catch (Exception e) {
            //renderManager.getOnDemandRenderer("ReservasView").requestRender();
            FacesUtils.addErrorMessage(e.getMessage());
            throw e;
        }

        return "";
    }

    public List<Reservas> getReservas() {
        if (flag) {
            try {
                reservas = BusinessDelegatorView.getReservas();
                flag = false;
            } catch (Exception e) {
                flag = true;
                FacesUtils.addErrorMessage(e.getMessage());
            }
        }

        return reservas;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setReservas(List<Reservas> reservas) {
        this.reservas = reservas;
    }

    public boolean isRenderDataTable() {
        try {
            if (flag) {
                if (BusinessDelegatorView.findTotalNumberReservas() > 0) {
                    renderDataTable = true;
                } else {
                    renderDataTable = false;
                }
            }

            flag = false;
        } catch (Exception e) {
            renderDataTable = false;
            e.printStackTrace();
        }

        return renderDataTable;
    }

    public DataModel getData() {
        state = PersistentFacesState.getInstance();

        if (onePageDataModel == null) {
            onePageDataModel = new LocalDataModel(pageSize);
        }

        return onePageDataModel;
    }

    /**
    * This is where the Object data is retrieved from the database and
    * returned as a list of objects for display in the UI.
    */
    private DataPage<Reservas> getDataPage(int startRow, int pageSize) {
        // Retrieve the total number of objects from the database.  This
        // number is required by the DataPage object so the paginator will know
        // the relative location of the page data.
        int totalNumberReservas = 0;

        try {
            totalNumberReservas = BusinessDelegatorView.findTotalNumberReservas()
                                                       .intValue();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Calculate indices to be displayed in the ui.
        int endIndex = startRow + pageSize;

        if (endIndex > totalNumberReservas) {
            endIndex = totalNumberReservas;
        }

        try {
            reservas = BusinessDelegatorView.findPageReservas(sortColumnName,
                    sortAscending, startRow, endIndex - startRow);

            // Remove this Renderable from the existing render groups.
            //leaveRenderGroups();        			
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Add this Renderable to the new render groups.
        //joinRenderGroups();
        // Reset the dirtyData flag.
        onePageDataModel.setDirtyData(false);
        // This is required when using Hibernate.  If the SessionManager is not
        // cleared or closed objects are cached and stale objects will show up
        // in the table.
        // This way, the detached objects are reread from the database.
        // This call is not required with Hibernate, which uses a Query Hint
        // to clear the l2 cache in the DAO.
        flag = true;

        return new DataPage<Reservas>(totalNumberReservas, startRow, reservas);
    }

    public DataModel getDataDTO() {
        state = PersistentFacesState.getInstance();

        if (onePageDataModel == null) {
            onePageDataModel = new LocalDataModelDTO(pageSize);
        }

        return onePageDataModel;
    }

    /**
    * This is where the Object data is retrieved from the database and
    * returned as a list of objects for display in the UI.
    */
    private DataPage<ReservasDTO> getDataPageDTO(int startRow, int pageSize) {
        // Retrieve the total number of objects from the database.  This
        // number is required by the DataPage object so the paginator will know
        // the relative location of the page data.
        int totalNumberReservas = 0;

        try {
            totalNumberReservas = BusinessDelegatorView.findTotalNumberReservas()
                                                       .intValue();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Calculate indices to be displayed in the ui.
        int endIndex = startRow + pageSize;

        if (endIndex > totalNumberReservas) {
            endIndex = totalNumberReservas;
        }

        try {
            reservas = BusinessDelegatorView.findPageReservas(sortColumnName,
                    sortAscending, startRow, endIndex - startRow);

            if (Utilities.validationsList(reservas)) {
                reservasDTO = new ArrayList<ReservasDTO>();

                for (Reservas reservasTmp : reservas) {
                    ReservasDTO reservasDTO2 = new ReservasDTO();
                    reservasDTO2.setCodReservas(reservasTmp.getCodReservas()
                                                           .toString());
                    reservasDTO2.setFechaEvento(reservasTmp.getFechaEvento());
                    reservasDTO2.setFechaReserva(reservasTmp.getFechaReserva());
                    reservasDTO2.setCodSala_Salaxtforma((reservasTmp.getSalaxtforma().getId()
                                                                    .getCodSala() != null)
                        ? reservasTmp.getSalaxtforma().getId().getCodSala().toString()
                        : null);
                    reservasDTO2.setCodTforma_Salaxtforma((reservasTmp.getSalaxtforma().getId()
                                                                      .getCodTforma() != null)
                        ? reservasTmp.getSalaxtforma().getId().getCodTforma().toString()
                        : null);
                    reservasDTO2.setCodSolicitude_SolEventos((reservasTmp.getSolEventos()
                                                                         .getCodSolicitude() != null)
                        ? reservasTmp.getSolEventos().getCodSolicitude()
                                     .toString() : null);
                    reservasDTO2.setLoggin_Usuarios((reservasTmp.getUsuarios()
                                                                .getLoggin() != null)
                        ? reservasTmp.getUsuarios().getLoggin().toString() : null);
                    reservasDTO2.setReservas(reservasTmp);
                    reservasDTO2.setReservasView(this);
                    reservasDTO.add(reservasDTO2);
                }
            }

            // Remove this Renderable from the existing render groups.
            leaveRenderGroups();
        } catch (Exception e) {
            FacesUtils.addErrorMessage(e.getMessage());
        }

        // Add this Renderable to the new render groups.
        joinRenderGroups();
        // Reset the dirtyData flag.
        onePageDataModel.setDirtyData(false);
        // This is required when using Hibernate.  If the SessionManager is not
        // cleared or closed objects are cached and stale objects will show up
        // in the table.
        // This way, the detached objects are reread from the database.
        // This call is not required with Hibernate, which uses a Query Hint
        // to clear the l2 cache in the DAO.
        flag = true;

        return new DataPage<ReservasDTO>(totalNumberReservas, startRow,
            reservasDTO);
    }

    protected boolean isDefaultAscending(String sortColumn) {
        return true;
    }

    /**
    * This method is called when a render call is made from the server. Render
    * calls are only made to views containing an updated record. The data is
    * marked as dirty to trigger a fetch of the updated record from the
    * database before rendering takes place.
    */
    public PersistentFacesState getState() {
        onePageDataModel.setDirtyData();

        return state;
    }

    /**
    * This method is called from faces-config.xml with each new session.
    */
    public void setRenderManager(RenderManager renderManager) {
        this.renderManager = renderManager;
    }

    public void renderingException(RenderingException arg0) {
        if (arg0 instanceof TransientRenderingException) {
        } else if (arg0 instanceof FatalRenderingException) {
            // Remove from existing Customer render groups.
            leaveRenderGroups();
        }
    }

    /**
    * Remove this Renderable from existing uiCustomerBeans render groups.
    * OnDemandRenderers are named/created using the underlying Customer Number.
    */
    private void leaveRenderGroups() {
        if (Utilities.validationsList(reservasDTO)) {
            for (ReservasDTO reservasTmp : reservasDTO) {
                renderManager.getOnDemandRenderer("ReservasView").remove(this);
            }
        }
    }

    /**
    * Add this Renderable to the new uiCustomerBeans render groups.
    * OnDemandRenderers are named/created using the underlying Customer Number.
    */
    private void joinRenderGroups() {
        if (Utilities.validationsList(reservasDTO)) {
            for (ReservasDTO reservasTmp : reservasDTO) {
                renderManager.getOnDemandRenderer("ReservasView").add(this);
            }
        }
    }

    public void dispose() throws Exception {
    }

    public RenderManager getRenderManager() {
        return renderManager;
    }

    public void setState(PersistentFacesState state) {
        this.state = state;
    }

    public HtmlInputText getTxtCodSala_Salaxtforma() {
        return txtCodSala_Salaxtforma;
    }

    public void setTxtCodSala_Salaxtforma(HtmlInputText txtCodSala_Salaxtforma) {
        this.txtCodSala_Salaxtforma = txtCodSala_Salaxtforma;
    }

    public HtmlInputText getTxtCodTforma_Salaxtforma() {
        return txtCodTforma_Salaxtforma;
    }

    public void setTxtCodTforma_Salaxtforma(
        HtmlInputText txtCodTforma_Salaxtforma) {
        this.txtCodTforma_Salaxtforma = txtCodTforma_Salaxtforma;
    }

    public HtmlInputText getTxtCodSolicitude_SolEventos() {
        return txtCodSolicitude_SolEventos;
    }

    public void setTxtCodSolicitude_SolEventos(
        HtmlInputText txtCodSolicitude_SolEventos) {
        this.txtCodSolicitude_SolEventos = txtCodSolicitude_SolEventos;
    }

    public HtmlInputText getTxtLoggin_Usuarios() {
        return txtLoggin_Usuarios;
    }

    public void setTxtLoggin_Usuarios(HtmlInputText txtLoggin_Usuarios) {
        this.txtLoggin_Usuarios = txtLoggin_Usuarios;
    }

    public SelectInputDate getTxtFechaEvento() {
        return txtFechaEvento;
    }

    public void setTxtFechaEvento(SelectInputDate txtFechaEvento) {
        this.txtFechaEvento = txtFechaEvento;
    }

    public SelectInputDate getTxtFechaReserva() {
        return txtFechaReserva;
    }

    public void setTxtFechaReserva(SelectInputDate txtFechaReserva) {
        this.txtFechaReserva = txtFechaReserva;
    }

    public HtmlInputText getTxtCodReservas() {
        return txtCodReservas;
    }

    public void setTxtCodReservas(HtmlInputText txtCodReservas) {
        this.txtCodReservas = txtCodReservas;
    }

    public HtmlCommandButton getBtnSave() {
        return btnSave;
    }

    public void setBtnSave(HtmlCommandButton btnSave) {
        this.btnSave = btnSave;
    }

    public HtmlCommandButton getBtnModify() {
        return btnModify;
    }

    public void setBtnModify(HtmlCommandButton btnModify) {
        this.btnModify = btnModify;
    }

    public HtmlCommandButton getBtnDelete() {
        return btnDelete;
    }

    public void setBtnDelete(HtmlCommandButton btnDelete) {
        this.btnDelete = btnDelete;
    }

    public HtmlCommandButton getBtnClear() {
        return btnClear;
    }

    public void setBtnClear(HtmlCommandButton btnClear) {
        this.btnClear = btnClear;
    }

    public void setRenderDataTable(boolean renderDataTable) {
        this.renderDataTable = renderDataTable;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public List<ReservasDTO> getReservasDTO() {
        return reservasDTO;
    }

    public void setReservasDTO(List<ReservasDTO> reservasDTO) {
        this.reservasDTO = reservasDTO;
    }

    public TimeZone getTimeZone() {
        return java.util.TimeZone.getDefault();
    }

    /**
    * A special type of JSF DataModel to allow a datatable and datapaginator
    * to page through a large set of data without having to hold the entire
    * set of data in memory at once.
    * Any time a managed bean wants to avoid holding an entire dataset,
    * the managed bean declares this inner class which extends PagedListDataModel
    * and implements the fetchData method. fetchData is called
    * as needed when the table requires data that isn't available in the
    * current data page held by this object.
    * This requires the managed bean (and in general the business
    * method that the managed bean uses) to provide the data wrapped in
    * a DataPage object that provides info on the full size of the dataset.
    */
    private class LocalDataModel extends PagedListDataModel {
        public LocalDataModel(int pageSize) {
            super(pageSize);
        }

        public DataPage<Reservas> fetchPage(int startRow, int pageSize) {
            // call enclosing managed bean method to fetch the data
            return getDataPage(startRow, pageSize);
        }
    }

    private class LocalDataModelDTO extends PagedListDataModel {
        public LocalDataModelDTO(int pageSize) {
            super(pageSize);
        }

        public DataPage<ReservasDTO> fetchPage(int startRow, int pageSize) {
            // call enclosing managed bean method to fetch the data
            return getDataPageDTO(startRow, pageSize);
        }
    }
}
